<?php
class ListingTagsController extends AppController {

	var $name = 'ListingTags';
	var $uses = array('ListingTag', 'Listing');
	
	// 86400 = 24 chasa | 864000 = 10 dena | 2592000 = 30 dena | 31536000 = 365 dena | 157680000 = 5 godini
	var $cacheAction = array(
 		'view' => '157680000'
 	);
	
	var $paginate = array(
		'ListingTag' => array(
	        'limit' => 10,
	        'order' => array(
	            'ListingTag.id' => 'DESC'
	        )
		),
		'Listing' => array(
			'joins' => array(
				array(
        			'table' => 'listing_tags_listings',
        			'alias' => 'ListingTagsListing',
        			'type' => 'inner',
        			'conditions' => array(
						'Listing.id = ListingTagsListing.listing_id',
        			)
    			),
    			array(
        			'table' => 'listing_tags',
        			'alias' => 'ListingTag',
        			'type' => 'inner',
        			'conditions' => array(
						'ListingTagsListing.listing_tag_id = ListingTag.id',
        			)
    			)
			),
	        'order' => array(
	            'Listing.id' => 'DESC',
	        ),
	        'limit' => 10
		)
    );
	
	/**
	 * ListingTag Model
	 *
	 * @var ListingTag
	 */
	var $ListingTag;
	
	/**
	 * Tyk zadavame spisaka na action-ite s publichen dostyp (action-ite bez authorizaciq)
	 */
	function __initPublicActions() {
		$this->Auth->allow(array(
			'init_db',
			'view'
		));
	}
	
	function beforeFilter() {
        parent::beforeFilter();
        
        $this->__initPublicActions();
    }
    
    function init_db() {
    	$this->loadModel('Group');
    	
    	$group =& $this->Group;
    	
    	//------------- root [id=1]
    	$group->id = 1;
    	
    	$this->Acl->allow($group, 'controllers');
    	//------------/ root [id=1]
    	
    	//------------- user [id=2]
    	$group->id = 2;
    	
    	$this->Acl->allow($group, 'controllers/ListingTags/view');
    	//------------/ user [id=2]
    	
    	echo "all done";
    	exit;
    }
	
	function view($url_title = null) {
		if (!$url_title) {
			$this->cakeError('error404');
			return;
		}
		
		$this->ListingTag->recursive = -1;
		$listingTag = $this->ListingTag->find(
			'first',
			array(
				'conditions' => array(
					'ListingTag.url_title' => $url_title
				)
			)
		);
		
		if (empty($listingTag)) {
			$this->cakeError('error404');
			return;
		}
		
		$paginateConditions = array(
			'Listing.is_active ' => 1,
			'ListingTag.id' => $listingTag["ListingTag"]["id"]
		);
		$listings = $this->paginate('Listing', $paginateConditions);
		$this->set('listings', $listings);

		$this->set('listingTag', $listingTag);
		
		//================================ meta_info_for_layout
		$meta_info_for_layout['head_title'] = ' '.$listingTag["ListingTag"]["name"].' онлайн,цени и фирми предлагащи '.$listingTag["ListingTag"]["name"].'';
		
		$meta_info_for_layout['meta_description'] = $listingTag["ListingTag"]["name"].' онлайн оферти,продукти и фирми предлагащи '.$listingTag["ListingTag"]["name"].'.Бизнес каталог с актуална информация за '.$listingTag["ListingTag"]["name"].'. ';
		 
		$meta_info_for_layout['meta_keywords'] = ' '.$listingTag["ListingTag"]["name"].', ';
		 
		if((!empty($this->params["named"]["page"])) && ($this->params["named"]["page"] != 1)) {
			$meta_info_for_layout['canonical'] =
			SITE_WEBROOT
			.'tags/'.$listingTag["ListingTag"]["url_title"]
			.'/page:'.$this->params["named"]["page"]
			;
		} else {
			$meta_info_for_layout['canonical'] =
			SITE_WEBROOT
			.'tags/'.$listingTag["ListingTag"]["url_title"]
			;
		}
		 
		$this->set('meta_info_for_layout', $meta_info_for_layout);
		//===============================/ meta_info_for_layout

		//================================ navigationBreadcrumbData
		$navigationBreadcrumbData[] = array(
		   	"",
			$listingTag["ListingTag"]["name"]
		);
		
		$this->set('navigationBreadcrumbData', $navigationBreadcrumbData);
		//===============================/ navigationBreadcrumbData
	}
    
	function admin_index() {
		$this->ListingTag->recursive = 0;
		$this->set('listing_tags', $this->paginate('ListingTag'));
	}

	function admin_add() {
		$this->ListingTag->set($this->data);
		$this->ListingTag->setValidation('admin_add');
		$fields_to_save = array(
			'url_title', 'name'
		);
		
		if (!empty($this->data)) {
			$this->data["ListingTag"] = $this->__trimData($this->data["ListingTag"]);
			if($this->ListingTag->validates()) {
				$this->data["ListingTag"]["url_title"] = Inflector::slug(mb_strtolower($this->data["ListingTag"]["name"], "UTF-8"), "-");
				
				$this->ListingTag->create();
				if ($this->ListingTag->save($this->data, true, $fields_to_save)) {
					$this->Session->setFlash('Тага е запаметен успешно');
					$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'listing_tags', 'action' => 'index'));
				} else {
					$this->Session->setFlash('Грешка: The ListingTag could not be saved. Please, try again.');
				}
			} else {
				$this->Session->setFlash('Грешка');
			}
		}
	}

	function admin_edit($id = null) {
		$this->ListingTag->idFieldValue = $id;
		$this->ListingTag->set($this->data);
		$this->ListingTag->setValidation('admin_edit');
		$fields_to_save = array(
			'is_active', 'url_title', 'name'
		);
		
		if (!$id && empty($this->data)) {
			$this->Session->setFlash('Невалиден таг');
			$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'listing_tags', 'action' => 'index'));
		}
		if (!empty($this->data)) {
			$this->data["ListingTag"] = $this->__trimData($this->data["ListingTag"]);
			
			if($this->ListingTag->validates()) {
				$this->data["ListingTag"]["url_title"] = Inflector::slug(mb_strtolower($this->data["ListingTag"]["name"], "UTF-8"), "-");
				
				if ($this->ListingTag->save($this->data, true, $fields_to_save)) {
					$this->Session->setFlash('Тага е запаметен успешно');
					$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'listing_tags', 'action' => 'index'));
				} else {
					$this->Session->setFlash('Грешка: The ListingTag could not be saved. Please, try again.');
				}
			} else {
				$this->Session->setFlash('Грешка');
			}
		}
		if (empty($this->data)) {
			$this->data = $this->ListingTag->read(null, $id);
		}
	}

	function admin_delete($id = null, $confirm = false) {
		if (!$id) {
			$this->Session->setFlash('Невалиден таг');
			$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'listing_tags', 'action' => 'index'));
		}
		
		$location = $this->ListingTag->read(null, $id);
		$this->set('location', $location);
		
		if($confirm) {
			if ($this->ListingTag->delete($id)) {
				$this->Session->setFlash('Тага е изтрит успешно');
				$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'listing_tags', 'action' => 'index'));
			}
			
			$this->Session->setFlash('Грешка: The ListingTag could not be deleted. Please, try again.');
			$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'listing_tags', 'action' => 'index'));
		}
	}
	
	function admin_addall() {
		$this->ListingTag->setValidation('admin_addall');
		
		$isError = false;
		$savedListingTags = array();
		
		if (!empty($this->data)) {
			$this->data["ListingTag"] = $this->__trimData($this->data["ListingTag"]);
			$allListingTagsString = trim($this->data["ListingTag"]["name"], " ,\t\n\r\0\x0B");

			if(!empty($allListingTagsString)) {
				
				unset($this->data["ListingTag"]);
					
				$allListingTagsExploded = explode(",", $allListingTagsString);
					
				foreach ($allListingTagsExploded as $currentListingTagName) {
					$currentListingTagName = trim($currentListingTagName, " ,\t\n\r\0\x0B");
					if($currentListingTagName != "") {
						$this->data["ListingTag"]["name"] = $currentListingTagName;
						$this->data["ListingTag"]["url_title"] = Inflector::slug(mb_strtolower($currentListingTagName, "UTF-8"), "-");
						
						$this->ListingTag->set($this->data);
						
						if($this->ListingTag->validates()) {
							$this->ListingTag->create();
							if(!$this->ListingTag->save($this->data)) {
								$isError = true;
								$this->Session->setFlash('Грешка: The ListingTag could not be saved. Please, try again.');
								break;
							} else {
								$savedListingTags[] = $currentListingTagName;
							}
						} else {
							$isError = true;
							$this->Session->setFlash('Грешка');
							break;
						}
					}
				}
				
				if(!$isError) {
					$this->Session->setFlash('Таговете са запаметени успешно');
					$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'listing_tags', 'action' => 'index'));
				}
			}
		}
		
		$this->set('isError', $isError);
		$this->set('savedListingTags', $savedListingTags);
	}
	
}
?>